package com.mkait.thief.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mkait.thief.domain.Order;
import com.mkait.thief.domain.RefundVerify;
import com.mkait.thief.mapper.RefundVerifyMapper;
import com.mkait.thief.service.OrderService;
import com.mkait.thief.service.RefundVerifyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
public class RefundVerifyServiceImpl extends ServiceImpl<RefundVerifyMapper, RefundVerify>
        implements RefundVerifyService {


    @Autowired
    private RefundVerifyMapper refundVerifyMapper;

    @Autowired
    private OrderService orderService;

    /**
     * 退款验证
     * @return
     */
    @Override
    public String verifyRefundService(String tradeNo) {
        //从request中获取sessionUserId
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        HttpServletResponse response = servletRequestAttributes.getResponse();
        String sessionUser = (String)request.getAttribute("sessionUser");
        //根据tradeNo获取订单信息
        LambdaQueryWrapper<Order> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderLambdaQueryWrapper.eq(Order::getTradeNo,tradeNo);
        Order order = orderService.getOne(orderLambdaQueryWrapper);
        //判断sessionUser是否是订单的userId或者proxyParentUserId
        if (sessionUser.equals(order.getUserId().toString()) || sessionUser.equals(order.getProxyParentUserId().toString())) {
            //根据tradeNo获取退款验证信息
            RefundVerify refundVerify = refundVerifyMapper.selectById(tradeNo);
            //判断退款验证信息是否存在
            if (refundVerify == null){
                return "订单信息有误";
            }
            //判断退款验证信息状态
            Integer status = refundVerify.getStatus();
            switch (status){
                case 0:
                    return "等待系统验证中，稍后再试";
                case 1:
                    return "验证错误，请联系管理员";
                case 2:
                    return "订单退款失败，请联系管理员";
                case 3:
                    return "订单退款成功";
            }
        }
        response.setStatus(403);
        return "没有权限";
    }
}
